import { useCallback, useEffect, useState } from 'react'
import { Card, Table, Space, message, Modal, Form, Input } from 'antd'
import { PlayCircleOutlined, PauseCircleOutlined } from '@ant-design/icons'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons'
import { ipcService } from '../../api/service'
import type { HomePageConfig, CrawlProgress } from '../../api/service'
import AuthButton from '../../components/common/AuthButton'
import { useTranslation } from 'react-i18next'
import './HomePage.css'

function HomePage() {
  const [homepages, setHomepages] = useState<HomePageConfig[]>([])
  const [crawlProgress, setCrawlProgress] = useState<Record<string, CrawlProgress>>({})
  const [isLoading, setIsLoading] = useState(false)
  const [addModalVisible, setAddModalVisible] = useState(false)
  const { t } = useTranslation()
  const [form] = Form.useForm()

  const loadHomePages = useCallback(async () => {
    setIsLoading(true)
    try {
      const data = await ipcService.getHomePages()
      // 从 ProfileListResponse 中提取 profiles 数组，并转换为 HomePageConfig 格式
      const profiles = (data.profiles || []).map(profile => ({
        ...profile,
        platform: profile.platform || 'unknown',
        name: profile.name || 'Untitled',
        createdAt: profile.createdAt || new Date().toISOString(),
        updatedAt: profile.updatedAt || new Date().toISOString()
      }))
      setHomepages(profiles)
    } catch (error) {
      console.error('Failed to load homepage list:', error)
      message.error(t('homePage.messages.loadFailed'))
    } finally {
      setIsLoading(false)
    }
  }, [t])

  useEffect(() => {
    loadHomePages()
  }, [loadHomePages])

  useEffect(() => {
    const removeProgressListener = ipcService.onCrawlProgress((progress: CrawlProgress) => {
      setCrawlProgress(prev => ({ ...prev, [progress.profileId]: progress }))
    })

    const removeResultListener = ipcService.onCrawlResult((result: any) => {
      message.success(
        t('homePage.messages.crawlCompleted', { count: result.videos?.length || 0 })
      )
      loadHomePages()
    })

    return () => {
      removeProgressListener()
      removeResultListener()
    }
  }, [loadHomePages, t])

  const handleCrawl = async (mainpage: HomePageConfig) => {
    try {
      await ipcService.startCrawl(mainpage.id)
      message.info(t('homePage.messages.crawlStarted'))
    } catch (error) {
      message.error(
        t('homePage.messages.crawlFailed', {
          error: error instanceof Error ? error.message : String(error)
        })
      )
    }
  }

  const handleStopCrawl = async (mainpageId: string) => {
    try {
      await ipcService.stopCrawl(mainpageId)
      message.info(t('homePage.messages.stopSuccess'))
    } catch (error) {
      message.error(
        t('homePage.messages.stopFailed', {
          error: error instanceof Error ? error.message : String(error)
        })
      )
    }
  }

  const showAddHomePageModal = () => {
    setAddModalVisible(true)
  }

  const handleAddCancel = () => {
    form.resetFields()
    setAddModalVisible(false)
  }

  const startDouyinFetch = async (url: string) => {
    try {
      console.log('Start fetching Douyin homepage:', url)
      await ipcService.addHomePage({ url })
      message.info(t('homePage.messages.addSuccess', { url }))
    } catch (error) {
      console.error('Fetch failed:', error)
      message.error(
        t('homePage.messages.fetchFailed', {
          error: error instanceof Error ? error.message : String(error)
        })
      )
    }
  }

  const handleAddConfirm = async () => {
    // 1. 获取表单参数
    // 2. 自动进行 urldecode
    // 3. 调用addHomePage主进程接口，然后主进程接口再调用后端 api，最终保存到 mysql
    // 4. 提示添加成功
    try {
      const values = await form.validateFields()
      const urls = values.urls.split('\n').filter((url: string) => url.trim())

      if (urls.length === 0) {
        message.error(t('homePage.messages.enterAtLeastOne'))
        return
      }

      

      const decodedUrls = urls.map((url: string) => {
        try {
          if (url.includes('%')) {
            return decodeURIComponent(url.trim())
          }
          return url.trim()
        } catch (error) {
          console.warn('URL decode failed, using original URL:', url)
          return url.trim()
        }
      })

      console.log('Add homepage URLs:', decodedUrls)

      for (const url of decodedUrls) {
        // eslint-disable-next-line no-await-in-loop
        await startDouyinFetch(url)
      }

      message.success(t('homePage.messages.startBatch', { count: decodedUrls.length }))
      form.resetFields()
      setAddModalVisible(false)
      loadHomePages()
    } catch (error) {
      console.error('Validation failed:', error)
    }
  }

  const handleBatchDelete = () => {
    // TODO: 实现批量删除逻辑
    message.info(t('homePage.messages.batchDeleteTodo'))
  }

  const columns = [
    {
      title: t('homePage.table.index'),
      dataIndex: 'index',
      key: 'index',
      width: 60,
      render: (_: any, __: HomePageConfig, index: number) => index + 1
    },
    {
      title: t('homePage.table.author'),
      dataIndex: 'author',
      key: 'author',
      width: 120,
      render: (author: string, record: HomePageConfig) => {
        const displayName = author || record.name
        return (
          <div className="homepage-manager-author">
            <div className="homepage-manager-author-name">{displayName}</div>
            <div className="homepage-manager-author-url">{record.url}</div>
          </div>
        )
      }
    },
    {
      title: t('homePage.table.followCount'),
      dataIndex: 'followCount',
      key: 'followCount',
      width: 100,
      render: (count: number) => count ? count.toLocaleString() : '-'
    },
    {
      title: t('homePage.table.fansCount'),
      dataIndex: 'fansCount',
      key: 'fansCount',
      width: 100,
      render: (count: number) => count ? count.toLocaleString() : '-'
    },
    {
      title: t('homePage.table.likesReceived'),
      dataIndex: 'likesReceived',
      key: 'likesReceived',
      width: 100,
      render: (count: number) => count ? count.toLocaleString() : '-'
    },
    {
      title: t('homePage.table.likesGiven'),
      dataIndex: 'likesGiven',
      key: 'likesGiven',
      width: 100,
      render: (count: number) => count ? count.toLocaleString() : '-'
    },
    {
      title: t('homePage.table.worksCount'),
      dataIndex: 'worksCount',
      key: 'worksCount',
      width: 100,
      render: (count: number) => count ? count.toLocaleString() : '-'
    },
    {
      title: t('homePage.table.lastWorkTime'),
      dataIndex: 'lastWorkTime',
      key: 'lastWorkTime',
      width: 150,
      render: (time: string) => time || '-'
    },
    {
      title: t('homePage.table.extractedWorksCount'),
      dataIndex: 'extractedWorksCount',
      key: 'extractedWorksCount',
      width: 120,
      render: (count: number) => count ? count.toLocaleString() : '-'
    },
    {
      title: t('homePage.table.localVideoCount'),
      dataIndex: 'localVideoCount',
      key: 'localVideoCount',
      width: 120,
      render: (count: number) => count ? count.toLocaleString() : '-'
    },
    {
      title: t('homePage.table.localImageTextCount'),
      dataIndex: 'localImageTextCount',
      key: 'localImageTextCount',
      width: 120,
      render: (count: number) => count ? count.toLocaleString() : '-'
    },
    {
      title: t('homePage.table.localLikedCount'),
      dataIndex: 'localLikedCount',
      key: 'localLikedCount',
      width: 120,
      render: (count: number) => count ? count.toLocaleString() : '-'
    },
    {
      title: t('homePage.table.remark'),
      dataIndex: 'remark',
      key: 'remark',
      width: 100,
      render: (remark: string) => remark || t('homePage.table.remarkDefault')
    },
    {
      title: t('homePage.table.addTime'),
      dataIndex: 'addTime',
      key: 'addTime',
      width: 150,
      render: (time: string) => time || '-'
    },
    {
      title: t('homePage.table.actions'),
      key: 'actions',
      width: 120,
      fixed: 'right' as const,
      render: (_: any, record: HomePageConfig) => {
        const progress = crawlProgress[record.id]
        const isCrawling = progress && progress.status === 'crawling'

        return (
          <Space>
            {isCrawling ? (
              <AuthButton
                danger
                icon={<PauseCircleOutlined />}
                onClick={() => handleStopCrawl(record.id)}
                size="small"
              >
                {t('homePage.actions.stop')}
              </AuthButton>
            ) : (
              <AuthButton
                type="primary"
                icon={<PlayCircleOutlined />}
                onClick={() => handleCrawl(record)}
                size="small"
              >
                {t('homePage.actions.crawl')}
              </AuthButton>
            )}
          </Space>
        )
      }
    }
  ]

  return (
    <div className="page-container">
      <Card className="content-card">
        <div className="homepage-manager">
          <div className="homepage-manager-header">
            <AuthButton
              type="primary"
              icon={<PlusOutlined className="homepage-manager-action-icon" />}
              onClick={showAddHomePageModal}
              className="homepage-manager-add-btn"
            >
              {t('homePage.actions.add')}
            </AuthButton>
            <AuthButton
              danger
              icon={<DeleteOutlined className="homepage-manager-action-icon" />}
              onClick={handleBatchDelete}
              className="homepage-manager-delete-btn"
            >
              {t('homePage.actions.batchDelete')}
            </AuthButton>
          </div>
          <div className="homepage-manager-table">
            <Table
              columns={columns}
              dataSource={homepages}
              rowKey="id"
              pagination={false}
              loading={isLoading}
              size="small"
              bordered
            />
          </div>
          <Modal
            title={t('homePage.modal.title')}
            open={addModalVisible}
            onOk={handleAddConfirm}
            onCancel={handleAddCancel}
            width={1000}
            okText={t('common.confirm')}
            cancelText={t('common.cancel')}
          >
            <Form
              form={form}
              layout="vertical"
              className="homepage-manager-form"
            >
              <Form.Item
                name="urls"
                label={t('homePage.form.label')}
                rules={[
                  { required: true, message: t('homePage.form.validation') }
                ]}
                extra={t('homePage.form.extra')}
              >
                <Input.TextArea
                  placeholder={t('homePage.form.placeholder')}
                  rows={6}
                  className="homepage-manager-textarea"
                  autoSize={{ minRows: 6, maxRows: 12 }}
                  spellCheck={false}
                  autoComplete="off"
                  autoCorrect="off"
                  autoCapitalize="off"
                />
              </Form.Item>
            </Form>
          </Modal>
        </div>
      </Card>
    </div>
  )
}

export default HomePage